//
//  DownLoadProgressTableViewCell.m
//  MapleLeaf
//
//  Created by WangZe on 15/11/30.
//  Copyright © 2015年 AntennaBabyTeam. All rights reserved.
//

#import "DownLoadProgressTableViewCell.h"
#define SWIDTH self.contentView.frame.size.width
#define SHEIGHT self.contentView.frame.size.height
#import "DownloadTool.h"
@implementation DownLoadProgressTableViewCell
{
    NSURLSession *urlSession;
    
    NSOperationQueue *queue;
    
    NSURLSessionDownloadTask *downloadTask;
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self createView];
    }
    return self;
}

- (void)setDic:(NSDictionary *)dic
{
    if (_dic != dic) {
        _dic = dic;
    }
    
    self.nameLabel.text = [NSString stringWithFormat:@"%@, %@", self.dic[@"name"], self.dic[@"num"]];
    self.downloadStateImageView.image = [UIImage imageNamed:@"123.jpg"];
    
    [self readfile];
    
    
}
- (void)readfile
{
    NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString *docPath = [sandBoxPath stringByAppendingPathComponent:[NSString stringWithFormat:@"Cartoon/%@",self.nameStr]];
    NSFileManager *manager = [NSFileManager defaultManager];
    
    // 判断是否存在文件夹
    if (![manager fileExistsAtPath:docPath]) {
        [manager createDirectoryAtPath:docPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString *downloadPath = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@.zip", self.dic[@"name"], self.dic[@"num"]]];
    if (![manager fileExistsAtPath:downloadPath]) {
        [self strat:self.dic[@"download"]];
    }
    else
    {
        self.myProgressView.progress = 1;
        self.downloadStateLabel.text = @"下载完成";
    }
}
// 执行下载任务时有数据写入
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    // 当前下载的数据          // 期望得到的数据
    double currentValue = totalBytesWritten / (double)totalBytesExpectedToWrite;
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"%f",currentValue);
        // 同步progressIndicator
        self.downloadStateLabel.text = @"下载中";
        self.myProgressView.hidden = NO;
        self.myProgressView.progress = currentValue;
        NSLog(@"%@", [NSThread currentThread]);
    });
}
- (void)setNameStr:(NSString *)nameStr
{
    if (_nameStr != nameStr) {
        _nameStr = nameStr;
    }
}

// 下载完成时执行的方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    self.downloadStateLabel.text = @"下载完成";
    
    // 寻找沙盒路径
    NSData *data = [NSData dataWithContentsOfURL:location];
    NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
 
    NSString *docPath = [sandBoxPath stringByAppendingPathComponent:[NSString stringWithFormat:@"Cartoon/%@",self.nameStr]];
    NSFileManager *manager = [NSFileManager defaultManager];
    
    // 判断是否存在文件夹
    if (![manager fileExistsAtPath:docPath]) {
        [manager createDirectoryAtPath:docPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString *downloadPath = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@.zip", self.dic[@"name"], self.dic[@"num"]]];
    [data writeToFile:downloadPath atomically:YES];
    
    // 创建文件管理者
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    //    [fileManager moveItemAtURL:location toURL:[NSURL URLWithString:file] error:nil];
    // 将tmp中的临时文件从文件夹中移除
    [fileManager removeItemAtURL:location error:NULL];
    
    
}



- (void)strat:(NSString *)str
{
    queue = [[NSOperationQueue alloc] init];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:str]];
    urlSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
//    [NSURLSession sessionWithConfiguration:<#(nonnull NSURLSessionConfiguration *)#> delegate:<#(nullable id<NSURLSessionDelegate>)#> delegateQueue:<#(nullable NSOperationQueue *)#>]
    downloadTask = [urlSession downloadTaskWithRequest:request];
    [downloadTask resume];
}


- (void)createView
{
    self.nameLabel = [[UILabel alloc] init];
    [self.contentView addSubview:self.nameLabel];
    
    self.myProgressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    [self.contentView addSubview:self.myProgressView];
    
    self.downloadStateLabel = [[UILabel alloc] init];
    [self.contentView addSubview:self.downloadStateLabel];
    
    self.downloadStateImageView = [[UIImageView alloc] init];
    [self.contentView addSubview:self.downloadStateImageView];
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    self.nameLabel.frame = CGRectMake(10, 5, SWIDTH - 10, 20);
    self.downloadStateLabel.frame = CGRectMake(10, 5, SWIDTH - 55, 20);
    self.downloadStateLabel.textAlignment = NSTextAlignmentRight;
    self.myProgressView.frame = CGRectMake(10, 25, SWIDTH - 55, 20);
    self.downloadStateImageView.frame = CGRectMake(SWIDTH - 35, 10, 30, 30);
    
}







- (void)awakeFromNib {
    // Initialization code
    
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
